package com.itheima.controller;

import com.itheima.common.R;
import com.itheima.common.Result;
import com.itheima.pojo.BsUser;
import com.itheima.pojo.hm.HmArticles;
import com.itheima.service.ArticlesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;

@RestController
@RequestMapping("/articles")
public class ArticlesController {


    @Autowired
    private ArticlesService articlesService;

    @Autowired
    private HttpServletRequest request;

    //todo 面试技巧分页查询
    @GetMapping()
    public Result findPage(Integer page,Integer pagesize,String keyword,Integer state){
        Result result = articlesService.findPage(page,pagesize,keyword,state);
        return result;
    }
    //todo 添加面试技巧数据
    @PostMapping()
    public void add(@RequestBody HmArticles hmArticles){
        HttpSession session = request.getSession();
        Integer userId = (Integer) session.getAttribute("userId");
        hmArticles.setCreatorID(2);
        hmArticles.setVisits("0");
        hmArticles.setCreateTime(LocalDateTime.now());
        articlesService.add(hmArticles);
    }
    //todo 启用禁用状态
    @PostMapping("/{id}/{status}")
    public R modifyStatus(@PathVariable Integer id,@PathVariable Integer status){
        return articlesService.modifyStatus(id,status);
    }
    //todo 删除
    @DeleteMapping("/{id}")
    public R deleteById(@PathVariable Integer id){
        return articlesService.deleteById(id);
    }
    //todo 编辑修改
    @PutMapping("/{id}")
    public R modify(@PathVariable Integer id,@RequestBody HmArticles hmArticles){
        return articlesService.modify(id,hmArticles);
    }
    //todo 文章详情
    @GetMapping("/{id}")
    public HmArticles findById(@PathVariable Integer id){
        HmArticles hmArticles = articlesService.findById(id);
        HttpSession session = request.getSession();
        Integer userId = (Integer) session.getAttribute("userId");

        BsUser bsUser = articlesService.findUserId(2);

        hmArticles.setCreatorID(2);
        hmArticles.setCreator(bsUser.getUsername());

        return hmArticles;
    }

}
